import { Argv } from "koishi"

export const name = "help-redirect"

const prefixes = {
  ">": "evaluate",
  "∪": "uiua",
  "¿¿": "whatcmd",
  "¿": "whatlang",
  "<|": "rpipeline",
  "< |": "rpipeline",
}

export async function apply(ctx) {
  function whatcmdHelp(origArgv, name) {
    const argv = Argv.parse("whatcmd help")
    argv.tokens.push({ inters: [], quoted: true, terminator: '', content: name })
    if (origArgv.root) argv.root = "-lnnbot-pseudo"
    return origArgv.session.execute(argv)
  }

  ctx.on("command/before-execute", async argv => {
    if (argv.command.name === "help") try {
      if (argv.args[0]?.match(/^¿¿./))
        return whatcmdHelp(argv, argv.args[0].slice(2))

      const args = argv.args.join(" ").split(" ")

      if (args.length > 1 && ctx.$commander.get(args[0]?.toLowerCase().replaceAll("_", "-"))?.name === "whatcmd")
        return whatcmdHelp(argv, args[1])

      for (const prefix of Object.keys(prefixes).sort((a, b) => b.length - a.length)) {
        if (args.join(" ").startsWith(prefix)) {
          return argv.session.execute(Object.assign(argv, { args: [prefixes[prefix]], root: argv.root && "-lnnbot-pseudo" }), true)
        }
      }

      let resolved
      while (
        args.length > 1 &&
        (p = ctx.$commander.get(args[0].toLowerCase().replaceAll("_", "-"))) &&
        ctx.$commander.get(p.name + "." + args[1].toLowerCase().replaceAll("_", "-"))
      ) {
        args.unshift(args.splice(0, 2).join("."))
        resolved = true
      }
      if (resolved) return argv.session.execute(Object.assign(argv, { args: [args[0]], root: argv.root && "-lnnbot-pseudo" }), true)
    } catch (err) {
      ctx.logger.warn(err)
    }
  })
}
